package com.explore.demo.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.explore.demo.common.ResultResponse;
import com.explore.demo.config.JwtConfig;
import com.explore.demo.pojo.TblUser;
import com.explore.demo.mapper.TblUserMapper;
import com.explore.demo.service.TblUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.function.ServerResponse;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author scy
 * @since 2022-05-31
 */
@Service
public class TblUserServiceImpl extends ServiceImpl<TblUserMapper, TblUser> implements TblUserService {


    @Resource
    private TblUserMapper tblUserMapper;

    @Resource
    private JwtConfig jwtConfig;

    @Override
    public ResultResponse<Object> login(String phone, String password) {
        TblUser user = tblUserMapper.selectOne(new QueryWrapper<TblUser>().eq("phone", phone));
        if (user == null){
            return ResultResponse.createByErrorMessage("用户不存在");
        }
        if (!user.getPassword().equals(password)){
            return ResultResponse.createByErrorMessage("密码错误");
        }
        String token = jwtConfig.createToken(phone);
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("toekn", token);
        return ResultResponse.createBySuccessMessage("success", 200, map);
    }

    @Override
    public ResultResponse<Object> register(String phone, String password) {
        TblUser user = tblUserMapper.selectOne(new QueryWrapper<TblUser>().eq("phone", phone));
        if (user != null){
            return ResultResponse.createByErrorMessage("用户名重复");
        }
        TblUser u = new TblUser();
        u.setPhone(phone)
                .setPassword(password);
        return tblUserMapper.insert(u) == 0 ?
                ResultResponse.createByErrorMessage("注册失败"):
                ResultResponse.createBySuccessMessage("注册成功");
    }

    @Override
    public ResultResponse<Object> updateUserInfo(TblUser user){
        return tblUserMapper.updateById(user) == 0 ?
                ResultResponse.createByErrorMessage("更新失败") : ResultResponse.createBySuccessMessage("更新成功");
    }

    @Override
    public ResultResponse<Object> queryUserInfo(String username,Integer offset, Integer total){
        QueryWrapper<TblUser> wrapper = new QueryWrapper<TblUser>().like("username", username);
        Page<TblUser> tblUserPage = tblUserMapper.selectPage(new Page<>(offset, total), wrapper);
        return ResultResponse.createBySuccessMessage("success", 200, tblUserPage.getRecords());
    }
}
